package com.wiscamp.ninechapters.problems.math;

import lombok.Data;
import lombok.EqualsAndHashCode;

import java.util.ArrayList;
import java.util.Collection;

/**
 * 乘除法运算不等式
 */
@Data
@EqualsAndHashCode(callSuper = true)
public class LatexTimesDivisionInequality extends LatexText {
    public LatexTimesDivisionInequality(String latexText) {
        this.textValue = latexText;
        this.latexType = LatexTextEnum.TIMES_DIVISION_INEQUALITY;
    }


    /**
     * 移除表达式中的括号 暂时不考虑括号嵌套
     *
     * @param expression 乘除法表达式
     * @param leftBrace  左括号
     * @param rightBrace 右括号
     * @return 移除括号后的表达式
     */
    private String removeBrace(String expression, String leftBrace, String rightBrace) {
        var tempText = expression.replace(" ", "").trim();
        tempText = tempText.replace(leftBrace, "");
        tempText = tempText.replace(rightBrace, "");
        return tempText;
    }

    /**
     * @return
     */
    @Override
    public Collection<String> toTerms() {
        Collection<String> terms = new ArrayList<>();
        String tempText = textValue;
        if (tempText.contains("(") || tempText.contains(")")) {
            // 表达式包含括号的情况，去括号
            tempText = removeBrace(tempText, "(", ")");
        }

        // 表达式不包含括号的情况
        // 6 × 2 ÷ 5 × 2 ÷ 7
        tempText = tempText.replace(" ", "").trim();
        StringBuilder builder = new StringBuilder();
        for (var character : tempText.toCharArray()) {
            if ((character == '×') || (character == '÷')) {
                terms.add(builder.toString());
                builder = new StringBuilder();
                builder.append(character);
            } else {
                builder.append(character);
            }
        }
        terms.add(builder.toString());

        Collection<String> resultTerms = new ArrayList<>();
        for (var term : terms) {
            if (!term.startsWith("×") && !term.startsWith("÷")) {
                resultTerms.add("×" + term);
            } else {
                resultTerms.add(term);
            }
        }
        return resultTerms;
    }
}
